package com.zonhar.autofeed.common.device.i2c;

import cn.hutool.extra.mail.MailUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zonhar.autofeed.entities.entity.DistConfigEntity;
import com.zonhar.autofeed.service.DistConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class PcaTask {

    private final static Logger log = LoggerFactory.getLogger(PcaTask.class);


    @Autowired
    private DistConfigService distConfigService;

    /**
     * 异步投喂
     * @param releaseNum
     */
    @Async
    public void  releaseFeed(Integer releaseNum){
        try {
            //驱动陀机下粮
            for (Integer i = 0; i < releaseNum; i++) {
                Pca9685DeviceUtils.run();
                Thread.sleep(100);
            }
            MailUtil.send(getSendEmail(), "猫粮自动投喂机通知", String.format("手动下粮%s份成功", releaseNum), false);
        } catch (InterruptedException ie) {
            log.error(ie.getMessage());
        }
    }

    /**
     * 获取收件人
     *
     * @return
     */
    private String getSendEmail() {
        QueryWrapper<DistConfigEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dist_name", "email");
        queryWrapper.eq("dist_group", "params");
        DistConfigEntity configEntity = distConfigService.getOne(queryWrapper);
        return configEntity.getDistValue();
    }

}
